<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 可选的Bootstrap主题文件（一般不使用） -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"></script>
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <nav class="navbar navbar-default" role="navigation">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> <a class="navbar-brand" href="/home">个人博客</a>
                </div>
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li class="active">
                            <a href="/home">主页</a>
                        </li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">博文<strong class="caret"></strong></a>
                            <ul class="dropdown-menu">
                                <li>
                                    <a href="/writingArticle">写博文</a>
                                </li>
                                <li class="divider">
                                </li>
                                <li>
                                    <a href="/articleList">文章列表</a>
                                </li>
                            </ul>
                        </li>
                        <li>
                            <a href="#">待开发</a>
                        </li>
                    </ul>
                    <form class="navbar-form navbar-left" role="search">
                        <div class="form-group">
                            <input type="text" class="form-control" />
                        </div>
                        <button type="submit" class="btn btn-default">搜索（待开发）</button>
                    </form>
                    <ul class="nav navbar-nav navbar-right">
                        <li>
                            <a href="#">链接（待开发）</a>
                        </li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">我的账号<strong class="caret"></strong></a>
                            <ul class="dropdown-menu">
                                <li>
                                    <a href="#">待开发</a>
                                </li>
                                <li class="divider">
                                </li>
                                <li>
                                    <a href="/logout">登出账号</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </nav>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            文章列表
        </div>
        <table class="table">
            <thead>
            <th width="20%">标题</th>
            <th width="20%">作者</th>
            <th>时间</th>
            <th width="20%">操作</th>
            </thead>
            <tbody id="tableBody">
            </tbody>
        </table>
        <!--分页导航栏-->
        <div class="panel-heading">
            <div style="text-align: right;">
                共<span id="totalNumber" style="color: dodgerblue">0</span>条 当前第
                <span id="currentPage" style="color: black">1</span>/<span id="totalPage" style="color: black">1</span>页
                <button id="Previous" class="btn btn-default">上一页</button>
                <button id="Next" class="btn btn-default">下一页</button>

                <div class="btn-group">
                    <button type="button" class="btn btn-default dropdown-toggle"
                            data-toggle="dropdown">
                        <span id="lineNum">5</span> <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                        <li><a id="5_EachPage" href="#" onclick="changeLineNum(this.id)">5</a></li>
                        <li><a id="10_EachPage" href="#" onclick="changeLineNum(this.id)">10</a></li>
                        <li><a id="20_EachPage" href="#" onclick="changeLineNum(this.id)">20</a></li>
                        <li><a id="50_EachPage" href="#" onclick="changeLineNum(this.id)">50</a></li>
                    </ul>
                </div>

                跳至<input id="pageNumber" type="text" style="width: 78px">页
                <button id="goPage" type="button" class="btn btn-primary">GO</button>
            </div>
        </div>
    </div>
</div>
<script>
    allArticles = null; //所有文章
    lineNumEachPage = 5; //默认每一页有5行数据


    $(document).ready(function() {

        getAllArticles();
        beforePagination();
        Pagination($("#currentPage").text());


        //简单分页功能之go
        $("#goPage").click(function() {
            var pageNumber = $("#pageNumber").val().trim();
            if (articleEveryPage.length <= pageNumber) {
                Pagination(articleEveryPage.length);
            } else {
                Pagination(pageNumber);
            }

        });

        //简单分页功能之上一页
        $("#Previous").click(function() {
            var pageNumber = $("#currentPage").text();
            var previousPageNumber = parseInt(pageNumber) - 1;
            Pagination(previousPageNumber);
        });

        //简单分页功能之下一页
        $("#Next").click(function() {
            var pageNumber = $("#currentPage").text();
            var nextPageNumber = parseInt(pageNumber) + 1;
            Pagination(nextPageNumber);
        });

    });

    //改变表格中数据的行数
    function changeLineNum(id){
        if (id == "5_EachPage") {
            lineNumEachPage = 5;
        }else if (id == "10_EachPage") {
            lineNumEachPage = 10;
        }else if (id == "20_EachPage") {
            lineNumEachPage = 20;
        }else if (id == "50_EachPage") {
            lineNumEachPage = 50;
        }
        $("#lineNum").text(lineNumEachPage);
        beforePagination();
        Pagination($("#currentPage").text());
    }

    //分页并显示内容
    function Pagination(pageNum) {

        //拼写HTML代码
        var HTML_CODE = "";
        for (var i = 0; i < articleEveryPage[pageNum - 1].length; i++) {
            if (articleEveryPage[pageNum - 1][i] != null) {

                var nameProperty = "name=" + articleEveryPage[pageNum - 1][i].id; //用id作为a的name，方便后面获取是哪篇文章的id

                HTML_CODE +=
                    "<tr><td>" + articleEveryPage[pageNum - 1][i].title + "</td>" +
                    "<td>" + articleEveryPage[pageNum - 1][i].author + "</td>" +
                    "<td>" + getDate(articleEveryPage[pageNum - 1][i].date) + "</td>" +
                    // "<td><a " + nameProperty + " onclick='showArticle(this.name)'>" + "详情" + "</a></td>" +
                    "<td><a " + nameProperty + " onclick='showArticle(this.name)'>" + "详情" + "</a>"+
                    "<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
                    "<a " + nameProperty + " onclick='deleteArticle(this.name)'>" + "删除" + "</a>" + "</td></tr>"

            }
        }
        $("#tableBody").html(HTML_CODE);
        //显示总条数
        $("#totalNumber").text(allArticles.length);
        //显示当前页数
        $("#currentPage").text(pageNum);
        //显示总页数
        $("#totalPage").text(articleEveryPage.length);
    }

    //分页前处理
    function beforePagination() {
        var numEveryPage = lineNumEachPage; //一页五个
        articleEveryPage = new Array(); //每页多少篇文章（每次调用都需要初始化，所以放在方法里）

        if (allArticles.length % numEveryPage == 0) {
            for (var i = 0; i < allArticles.length / numEveryPage; i++) {
                articleEveryPage[i] = new Array();
                for (var j = 0; j < numEveryPage; j++) {
                    articleEveryPage[i][j] = allArticles[numEveryPage * i + j];
                }
            }
        } else {
            for (var i = 0; i < allArticles.length / numEveryPage; i++) {
                articleEveryPage[i] = new Array();
                for (var j = 0; j < numEveryPage; j++) {
                    if (numEveryPage * i + j + 1 <= allArticles.length) {
                        articleEveryPage[i][j] = allArticles[numEveryPage * i + j];
                    } else {
                        articleEveryPage[i][j] = null;
                    }
                }
            }
        }

        console.log(articleEveryPage);

    }

    //获取数据库中所有的文章
    function getAllArticles() {

        $.ajax({
            type: "post",
            // ..代表的应该是 http://localhost:8080
            url: "../requestAllArticles",
            dataType: "json",
            async: false,

            // //key/value格式
            // data: 'username=ha&password=123',
            success: function(data) {
                allArticles = data;
                console.log(allArticles);
            },
            error: function() {
                alert("后台请求失败");
            }
        });
    }

    //显示所选文章
    function showArticle(name) {
        window.location.href = "../readingArticle?id=" + name;
    }

    //删除所选文章
    function deleteArticle(name) {
        var confirmResult = window.confirm("你确定要删除这篇文章吗？"); // 弹出input框（位于对象顶层）

        var data = {
            //json格式
            "id":name
        };

        if (confirmResult) {
            $.ajax({
                type: "post",
                // ..代表的应该是 http://localhost:8080
                url: "../deleteArticle",
                data: JSON.stringify(data),
                contentType : 'application/json;charset=utf-8',
                dataType: "json",
                // //key/value格式
                // data: 'username=ha&password=123',
                success: function(data){
                    if (data.result){
                        alert("删除成功！");
                        location.reload();
                    }
                },
                error: function (data) {
                    alert("删除失败！");
                }

            });

        }
    }

    //时间戳转为正常显示的时间模样的操作
    function getDate(time) {
        var oDate = new Date(time),
            oYear = oDate.getFullYear(),
            oMonth = oDate.getMonth() + 1,
            oDay = oDate.getDate(),
            oHour = oDate.getHours(),
            oMin = oDate.getMinutes(),
            oSen = oDate.getSeconds(),
            oTime = oYear + '年' + getzf(oMonth) + '月' + getzf(oDay) + '日 ' + getzf(oHour) + '时' +
                getzf(oMin) + '分' + getzf(oSen) + '秒'; //最后拼接时间
        return oTime;
    };
    //补0操作
    function getzf(num) {
        if (parseInt(num) < 10) {
            num = '0' + num;
        }
        return num;
    }
</script>
</body>

</html>